package com.ja.openchat.ui.chat;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.ui.chat.adapter.ConversationMessageAdapter;
import com.ja.openchat.ui.chat.adapter.viewholder.MessageContentViewHolder;
import com.ja.openchat.ui.chat.adapter.viewholder.VideoMessageContentViewHolder;
import com.ja.openchat.ui.chat.ext.core.ConversationExtension;
import com.ja.openchat.ui.chat.group.ModifyFieldActivity;
import com.ja.openchat.ui.chat.listener.OnDeleteDialogListener;
import com.ja.openchat.ui.chat.multimsg.MultiMessageAction;
import com.ja.openchat.ui.chat.multimsg.MultiMessageActionManager;
import com.ja.openchat.ui.chat.remittance.TransferMoneyDetailActivity;
import com.ja.openchat.ui.contact.ContactDetailActivity;
import com.ja.openchat.ui.message.MsgFragment;
import com.ja.openchat.views.AvatarDiffCallBack;
import com.ja.openchat.views.BottomSelectionDialog;
import com.ja.openchat.views.ChatUserDialog;
import com.ja.openchat.views.ChooseListDialog;
import com.ja.openchat.views.ConversationInputPanel;
import com.ja.openchat.views.ExLinearLayoutManager;
import com.ja.openchat.views.GroupPostDialog;
import com.ja.openchat.views.InputAwareLayout;
import com.ja.openchat.views.KeyboardAwareLinearLayout;
import com.ja.openchat.views.OnChooseListListener;
import com.ja.openchat.views.RecyclerHeaderView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.ChatExCacheManager;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.call.CallManager;
import com.zy.openchat.core.model.config.AppConfigInfo;
import com.zy.openchat.core.model.contact.UpdateChatActionInfo;
import com.zy.openchat.core.model.file.FileInfo;
import com.zy.openchat.core.model.file.FileTaskInfo;
import com.zy.openchat.core.model.group.ChatOnlineMemberCountInfo;
import com.zy.openchat.core.model.group.GroupManagePermissionInfo;
import com.zy.openchat.core.model.group.GroupMemberInfo;
import com.zy.openchat.core.model.group.GroupSendInfo;
import com.zy.openchat.core.model.group.GroupUserInfo;
import com.zy.openchat.core.model.group.Group_ChatMemberStatus;
import com.zy.openchat.core.model.group.SuperGroupInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.ChatPermissions;
import com.zy.openchat.core.model.message.DeleteMessagesInfo;
import com.zy.openchat.core.model.message.MentionSpan;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.core.model.message.MessageReaction;
import com.zy.openchat.core.model.message.MessageReactionInfo;
import com.zy.openchat.core.model.message.PinMessage;
import com.zy.openchat.core.model.message.SecretChatInfo;
import com.zy.openchat.core.model.message.UiMessage;
import com.zy.openchat.core.model.remittance.RemittanceDetailInfo;
import com.zy.openchat.core.model.user.OrgUserInfo;
import com.zy.openchat.core.model.user.UserFullInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.Common;
import com.zy.openchat.util.DensityUtil;
import com.zy.openchat.util.UIUtils;
import com.zy.openchat.util.glide.GlideApp;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTouch;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.base.BaseActivity;

//群发
public class ConversationFragment extends Fragment implements
        KeyboardAwareLinearLayout.OnKeyboardShownListener,
        KeyboardAwareLinearLayout.OnKeyboardHiddenListener,
        ConversationMessageAdapter.OnPortraitClickListener,
        ConversationMessageAdapter.OnPortraitLongClickListener,
        ConversationInputPanel.OnConversationInputPanelStateChangeListener,
        ConversationMessageAdapter.OnMessageCheckListener, ConversationMessageAdapter.OnMessageReceiptClickListener {

    private static final String TAG = "convFragment";

    public static final int REQUEST_PICK_MENTION_CONTACT = 100;
    public static final int REQUEST_CODE_GROUP_VIDEO_CHAT = 101;
    public static final int REQUEST_CODE_GROUP_AUDIO_CHAT = 102;

    private ChatInfo conversation;
    private GroupSendInfo groupSendInfo;
    private boolean loadingNewMessage;
    private boolean shouldContinueLoadNewMessage = false;

    private static final int MESSAGE_LOAD_AROUND = 20;
    private static final int MAX_MESSAGE_LOAD_AROUND = 100;

    @BindView(R.id.rootLinearLayout)
    InputAwareLayout rootLinearLayout;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.msgRecyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.group_send_layout)
    LinearLayout groupSendLayout;
    @BindView(R.id.title_users)
    TextView titleUsers;
    @BindView(R.id.recive_users_name)
    TextView reciveUsersName;

    @BindView(R.id.inputPanelFrameLayout)
    ConversationInputPanel inputPanel;
    @BindView(R.id.tv_notification)
    TextView tvNotification;
    @BindView(R.id.layout_announcement)
    ConstraintLayout layoutAnnouncement;
    @BindView(R.id.iv_close)
    ImageView imgClose;

    @BindView(R.id.multiMessageActionContainerLinearLayout)
    LinearLayout multiMessageActionContainerLinearLayout;

    @BindView(R.id.unreadCountLinearLayout)
    LinearLayout unreadCountLinearLayout;
    @BindView(R.id.unreadCountTextView)
    TextView unreadCountTextView;
    @BindView(R.id.unreadMentionCountTextView)
    TextView unreadMentionCountTextView;
    @BindView(R.id.unreadCountView)
    View unreadCountView;
    @BindView(R.id.unreadMentionCountView)
    View unreadMentionCountView;
    @BindView(R.id.group_hint_text)
    TextView groupHintText;
    @BindView(R.id.recycler_header)
    RecyclerHeaderView recycler_header;
    @BindView(R.id.chat_secret_tip_text)
    TextView chat_secret_tip_text;
    @BindView(R.id.moshengLayout)
    View moshengLayout;
    @BindView(R.id.pingbiUserBtn)
    TextView pingbiUserBtn;
    @BindView(R.id.secret_status_view)
    View secretStatusView;
    @BindView(R.id.secret_status_text)
    TextView secretStatusText;
    @BindView(R.id.secretView)
    View secretView;
    @BindView(R.id.secret_title_text)
    TextView secret_title_text;

    private ConversationMessageAdapter adapter;
    private boolean moveToBottom = true;
    private MessageViewModel messageViewModel;

    private Handler handler;
    private long firstUnreadMessageId = 0;
    private String conversationTitle = "";
    private LinearLayoutManager layoutManager;
    private String annContentStr;

    public GroupSendInfo getGroupSendInfo() {
        return groupSendInfo;
    }

    private boolean canEditGroupSetting;
    private Observer<SuperGroupInfo> groupInfoObserver = new Observer<SuperGroupInfo>() {
        @Override
        public void onChanged(SuperGroupInfo superGroupInfo) {
            if(superGroupInfo!=null&&conversation!=null&&superGroupInfo.id == conversation.superGroupId()&&superGroupInfo.status!=null){
                setRightTitle(conversation.isGroup()?conversation.getGroupCount(messageViewModel.getSuperGroupInfo()):"");
                messageViewModel.syncGroupNotice(conversation);
                setTitle();
                canEditGroupSetting = messageViewModel.canEditGroupSetting(superGroupInfo);
                Group_ChatMemberStatus status = superGroupInfo.status;
                switch (status.getMemberState()){
                    case GroupMemberState_Administrator:
                        canSendMessage();
                        break;
                    case GroupMemberState_Creator:
                        if(!status.is_member){
                            ban_SendMessage(getString(R.string.you_not_in_the_group));
                        }else{
                            canSendMessage();
                        }
                        break;
                    case GroupMemberState_Left:
                        ban_SendMessage(getString(R.string.you_not_in_the_group));
                        break;
                    case GroupMemberState_Member:
                        if(conversation!=null&&conversation.permissions!=null&&conversation.permissions.can_send_messages){
                            canSendMessage();
                        }else{
                            ban_SendMessage(getString(R.string.all_ban_send_word));
                        }
                        break;
                    case GroupMemberState_Banned:
                        ban_SendMessage(getString(R.string.you_not_in_the_group));
                        break;
                    case GroupMemberState_Restricted:
                        ban_SendMessage(getString(R.string.you_ban_send_word));
                        break;
                }
            }
        }
    };


    private Observer<String> announcementTitleObserver = new Observer<String>() {
        @Override
        public void onChanged(String s) {
            if(!TextUtils.isEmpty(s)) {
                annContentStr = s;
                layoutAnnouncement.setVisibility(View.VISIBLE);
                tvNotification.setText(s);
            }else{
                layoutAnnouncement.setVisibility(View.GONE);
            }
            if(!conversation.isGroup()){
                layoutAnnouncement.setVisibility(View.GONE);
            }
        }
    };


    private void handleSecretChat(){
        if(conversation==null||!conversation.isSecretChat()){
            secretStatusView.setVisibility(View.GONE);
            secretView.setVisibility(View.GONE);
            return;
        }
        TelegramManager.getTelegramManager().getSecretChat(getContext(), conversation.secretChatId(), new TgResultBlock<SecretChatInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, SecretChatInfo obj) {
                updateSecretChatInfo(obj);
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }
    private RecyclerView.AdapterDataObserver secretChatObserver = null;
    private void updateSecretChatInfo(SecretChatInfo secretChatInfo){
        if(secretChatInfo==null||conversation==null){
            secretStatusView.setVisibility(View.GONE);
            secretView.setVisibility(View.GONE);
            return;
        }
        if(secretChatObserver == null){
            secretChatObserver = new RecyclerView.AdapterDataObserver() {
                @Override
                public void onItemRangeInserted(int positionStart, int itemCount) {
                    super.onItemRangeInserted(positionStart, itemCount);
                    secretView.setVisibility(adapter.getItemCount()>0?View.GONE:View.VISIBLE);
                }

                @Override
                public void onItemRangeRemoved(int positionStart, int itemCount) {
                    super.onItemRangeRemoved(positionStart, itemCount);
                    secretView.setVisibility(adapter.getItemCount()>0?View.GONE:View.VISIBLE);
                }

                @Override
                public void onChanged() {
                    super.onChanged();
                    secretView.setVisibility(adapter.getItemCount()>0?View.GONE:View.VISIBLE);
                }
            };
        }
        try {
            adapter.registerAdapterDataObserver(secretChatObserver);
        }catch (Exception e){
            e.printStackTrace();
        }
        UserInfo userInfo = UserInfo.getUserInfo(conversation.userId());
        secret_title_text.setText(String.format(secretChatInfo.is_outbound?getString(R.string.invite_somebody_in_private_chat):getString(R.string.somebody_invite_you_in_private_chat),userInfo==null?getString(R.string.user_text):userInfo.displayName()));
        secretView.setVisibility(adapter.getItemCount()>0?View.GONE:View.VISIBLE);
        if(secretChatInfo.isClosed()){
            ToastUtils.showShort(getString(R.string.private_chat_closed));
            getActivity().finish();
        }else if(secretChatInfo.isReady()){
            secretStatusView.setVisibility(View.GONE);
            inputPanel.setVisibility(View.VISIBLE);
            canSendMessage();
        }else{
            secretView.setVisibility(View.VISIBLE);
            secretStatusView.setVisibility(View.VISIBLE);
            secretStatusView.setOnClickListener(null);
            secretStatusText.setText(String.format(getString(R.string.wait_somebody_online),userInfo==null?getString(R.string.user_text):userInfo.displayName()));
            ban_SendMessage(null);
        }
    }

    private void canSendMessage(){
        groupHintText.setVisibility(View.GONE);
        inputPanel.setVisibility(View.VISIBLE);
    }

    private void ban_SendMessage(String message){
        if(!TextUtils.isEmpty(message)){
            groupHintText.setText(message);
            groupHintText.setVisibility(View.VISIBLE);
        }else{
            groupHintText.setVisibility(View.GONE);
        }
        inputPanel.setVisibility(View.GONE);

    }

    private Observer<UiMessage> messageLiveDataObserver = new Observer<UiMessage>() {
        @Override
        public void onChanged(@Nullable UiMessage uiMessage) {
            appendNewMessage(uiMessage);
        }
    };


    private void appendNewMessage(UiMessage uiMessage){
        if (!isMessageInCurrentConversation(uiMessage)) {
            return;
        }
        if (isDisplayableMessage(uiMessage)) {
            // 消息定位时，如果收到新消息、或者发送消息，需要重新加载消息列表
            if (shouldContinueLoadNewMessage) {
                shouldContinueLoadNewMessage = false;
                reloadMessage();
                return;
            }
            AppConfigInfo configInfo = AppConfigInfo.getAppWithoutLoginConfigInfo();
            SuperGroupInfo super_groupInfo = messageViewModel.getSuperGroupInfo();
            TelegramManager.GroupMemberState state = null;
            if(super_groupInfo != null){
                state = super_groupInfo.status.getMemberState();
            }
            if(uiMessage.message.messageType ==  TelegramManager.MessageType.MessageType_Text_Screenshot){
                if(configInfo==null||configInfo.enabled_screenshot_notification){
                    adapter.addNewMessage(uiMessage);
                }else{
                    return;
                }
            }else if(uiMessage.message.content.type.equals("messageChatDeleteMember")){
                if(configInfo==null||configInfo.shown_everyone_member_changes){
                    adapter.addNewMessage(uiMessage);
                }else{
                    if (state == TelegramManager.GroupMemberState.GroupMemberState_Administrator || state == TelegramManager.GroupMemberState.GroupMemberState_Creator) {
                        //管理展示
                        adapter.addNewMessage(uiMessage);
                    }else{
                        return;
                    }
                }
            }else{
                adapter.addNewMessage(uiMessage);
            }

            if (moveToBottom || uiMessage.message.sender_user_id() == UserInfo.getUserInfo().id) {
                UIUtils.postTaskDelay(() -> {

                            int position = adapter.getItemCount() - 1;
                            if (position < 0) {
                                return;
                            }
                            recyclerView.scrollToPosition(position);
                        },
                        100);
            }
        }
    }
    private Observer<UiMessage> messageUpdateLiveDatObserver = new Observer<UiMessage>() {
        @Override
        public void onChanged(@Nullable UiMessage uiMessage) {
            if (!isMessageInCurrentConversation(uiMessage)) {
                return;
            }
            resetVideoView();
            if (isDisplayableMessage(uiMessage)) {
                adapter.updateMessage(uiMessage);
            }
        }
    };

    private Observer<Pair<Long,String>> groupSubTitleObserver = new Observer<Pair<Long,String>>() {
        @Override
        public void onChanged(@Nullable Pair<Long,String> subTitles) {
            if(subTitles!=null&&conversation!=null&&subTitles.first == conversation.superGroupId()){
                if(getActivity()!=null&&getActivity() instanceof ChatActivity){
                    ((ChatActivity)getActivity()).setSubTitle(subTitles.second);
                }
            }
        }
    };

    private boolean isMessageInCurrentConversation(UiMessage message) {
        if (message == null || message.message == null) {
            return false;
        }
        return isMessageInCurrentConversation(message.message.chat_id);
    }

    private boolean isMessageInCurrentConversation(long messageChatId) {
        if (conversation == null) {
            return false;
        }
        return conversation.id == messageChatId;
    }

    private boolean isDisplayableMessage(UiMessage uiMessage) {
        return uiMessage.message.id != 0;
    }

    private Observer<Map<String, String>> mediaUploadedLiveDataObserver = new Observer<Map<String, String>>() {
        @Override
        public void onChanged(@Nullable Map<String, String> stringStringMap) {
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("sticker", Context.MODE_PRIVATE);
            for (Map.Entry<String, String> entry : stringStringMap.entrySet()) {
                sharedPreferences.edit()
                        .putString(entry.getKey(), entry.getValue())
                        .apply();
            }

        }
    };

    public ConversationInputPanel getConversationInputPanel() {
        return inputPanel;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_conversation, container, false);
        ButterKnife.bind(this, view);
        initView();
        if(getArguments()!=null){
            conversation = getArguments().getParcelable("conversation");
            if(getArguments().getSerializable("userInfos")!=null){
                groupSendInfo = (GroupSendInfo) getArguments().getSerializable("userInfos");
            }
            if(conversation!=null){
                setupConversation(conversation);
            }
            if(groupSendInfo!=null&&!groupSendInfo.isEmpty()){
                groupSendLayout.setVisibility(View.VISIBLE);
                titleUsers.setText(String.format(getString(R.string.send_msg_to_amount_user),groupSendInfo.userIds.size()));
                reciveUsersName.setText(groupSendInfo.userNames());
            }else{
                groupSendLayout.setVisibility(View.GONE);
            }
        }
        return view;
    }

    private boolean isNeedRefrshData = true;

    @Override
    public void onResume() {
        super.onResume();
        if(isNeedRefrshData){
            setAddUserView(true);
        }
        if(conversation != null){
            messageViewModel.syncGroupNotice(conversation);
        }

        if(conversation != null && !conversation.isGroup()){
            layoutAnnouncement.setVisibility(View.GONE);
        }
    }

    public void initView() {
        canSendMessage();
        imgClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                layoutAnnouncement.setVisibility(View.GONE);
            }
        });
        layoutAnnouncement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置群组公告
                ModifyFieldActivity.start_setGroupNotice(getActivity(), conversation.id, annContentStr, canEditGroupSetting);
            }
        });
        chat_secret_tip_text.setText(String.format(getString(R.string.chat_secret_tip), getString(R.string.app_name)));
        handler = new Handler();
        rootLinearLayout.addOnKeyboardShownListener(this);
        swipeRefreshLayout.setOnRefreshListener(() -> {
            if (adapter.getMessages() == null || adapter.getMessages().isEmpty()) {
                swipeRefreshLayout.setRefreshing(false);
                return;
            }
            loadMoreOldMessages();
        });

        // message list
        adapter = new ConversationMessageAdapter(this);
        adapter.setOnPortraitClickListener(this);
        adapter.setOnMessageReceiptClickListener(this);
        adapter.setOnPortraitLongClickListener(this);
        adapter.setOnMessageCheckListener(this);
        layoutManager = new ExLinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // 向上滑动，不在底部，收到消息时，不滑动到底部, 发送消息时，可以强制置为true
                if (newState != RecyclerView.SCROLL_STATE_IDLE) {
                    return;
                }
                autoPlayVideo(recyclerView);
                if (!recyclerView.canScrollVertically(1)) {
                    moveToBottom = true;
                    if ((firstUnreadMessageId != 0 ) && !loadingNewMessage && shouldContinueLoadNewMessage) {
                        int lastVisibleItem = layoutManager.findLastCompletelyVisibleItemPosition();
                        if (lastVisibleItem > adapter.getItemCount() - 3) {
                            loadMoreNewMessages();
                        }
                    }
                } else {
                    moveToBottom = false;
                }
            }
        });

        inputPanel.init(this, rootLinearLayout);
        inputPanel.setOnConversationInputPanelStateChangeListener(this);
        messageViewModel = ViewModelProviders.of(this).get(MessageViewModel.class);
        messageViewModel.messageLiveData().observeForever(messageLiveDataObserver);
        messageViewModel.messageUpdateLiveData().observeForever(messageUpdateLiveDatObserver);
        messageViewModel.groupSubTitleLiveData().observeForever(groupSubTitleObserver);
        messageViewModel.mediaUpdateLiveData().observeForever(mediaUploadedLiveDataObserver);
        messageViewModel.groupInfoLiveData().observeForever(groupInfoObserver);
        messageViewModel.getAnnouncementTitle().observeForever(announcementTitleObserver);
//        initVideoView();
    }


    public void scrollToMessagePositionById(long focusMessageId,boolean isClickQuote){
        if (adapter.getItemCount() > 1) {
            int initialMessagePosition;
            if (focusMessageId != 0) {
                initialMessagePosition = adapter.getMessagePosition(focusMessageId);
                if (initialMessagePosition != -1) {
                    recyclerView.scrollToPosition(initialMessagePosition);
                    if(isClickQuote){
                        adapter.highlightFocusMessage(initialMessagePosition);
                    }
                }else{
                    loadMoreOldMessages(focusMessageId,isClickQuote);
                }
            }
        }
    }

    private void resetVideoView(){
        if(lastPlayHolder!=null){
            lastPlayHolder.resetVideoView();
        }
        lastPlayHolder = null;
    }

    private Rect rect = new Rect();
    private void autoPlayVideo(RecyclerView view) {
        if (view == null) return;
        //遍历RecyclerView子控件,如果mPlayerContainer完全可见就开始播放
        int count = view.getChildCount();
        for (int i = 0; i < count; i++) {
            View itemView = view.getChildAt(i);
            if (itemView == null) continue;
            MessageContentViewHolder holder = (MessageContentViewHolder) itemView.getTag();
            if(holder!=null&&holder instanceof VideoMessageContentViewHolder){
                VideoMessageContentViewHolder videoHolder = (VideoMessageContentViewHolder)holder;

                videoHolder.imageView.getLocalVisibleRect(rect);
                int height = videoHolder.imageView.getHeight();
                if (rect.top == 0 && rect.bottom == height) {
                    videoHolder.loadVideoCover();
                    startPlay(videoHolder);
                    break;
                }else{
                    videoHolder.loadVideoCover();
                    videoHolder.resetVideoView();
                }
            }

        }
    }

    public boolean isCurrentPlayingPosition(VideoMessageContentViewHolder holder){
        return lastPlayHolder == holder;
    }

    private VideoMessageContentViewHolder lastPlayHolder = null;

    private void startPlay(VideoMessageContentViewHolder videoHolder){
        if(videoHolder==null||videoHolder.getMessageInfo()==null||!videoHolder.getMessageInfo().isVideoFileDownloaded()){
            return;
        }
        if(lastPlayHolder == videoHolder){
            lastPlayHolder.pausePlayVideo();
            return;
        }else{
            resetVideoView();
        }
        lastPlayHolder = videoHolder;
        lastPlayHolder.playVideo();
    }

    private void setChatBg(){
        if(conversation==null){
            return;
        }
        if(ChatExCacheManager.getChatExCacheManager().chatBgIsFromMipmap(conversation.id)){
            int bgResId = ChatExCacheManager.getChatExCacheManager().chatMipmapBg(conversation.id);
            if(bgResId!=0){
                swipeRefreshLayout.setBackgroundResource(bgResId);
            }
        }else if(ChatExCacheManager.getChatExCacheManager().chatBgIsFromLocalFile(conversation.id)){
            String bg = ChatExCacheManager.getChatExCacheManager().chatLocalFileBg(conversation.id);
            if(!TextUtils.isEmpty(bg)){
                GlideApp.with(this)
                        .asDrawable()
                        .load(bg)
                        .into(new SimpleTarget<Drawable>() {
                            @Override
                            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                swipeRefreshLayout.setBackground(resource);
                            }
                        });
            }
        }else{
            swipeRefreshLayout.setBackground(null);
        }
    }
    private void reloadCenterTitle(){
        this.conversationTitle = conversation.isMyFovChat()?getString(R.string.my_collection_text):(conversation.isGroup()||conversation.isGroupSendChat())?conversation.title:UserInfo.getUserInfo(conversation.userId())==null?"":UserInfo.getUserInfo(conversation.userId()).displayName();
    }

    public void setupConversation(ChatInfo conversation) {
        this.conversation = conversation;
        reloadCenterTitle();
        setChatBg();
        inputPanel.setupConversation(conversation);
        loadMessage();
        setRightTitle("");
        setTitle();
        messageViewModel.loadGroupInfo(getContext(),conversation);
        messageViewModel.loadGroupMembers(getContext(),conversation);
        if(!conversation.isGroup()&&!conversation.isMyFovChat()&&!conversation.isGroupSendChat()){
            recycler_header.setVisibility(View.VISIBLE);
            recycler_header.attachTo(recyclerView);
        }else{
            recycler_header.setVisibility(View.GONE);
            recycler_header.detach();
        }
        if(secretChatObserver!=null){
            try {
                adapter.unregisterAdapterDataObserver(secretChatObserver);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        orgUserInfo = null;
        userFullInfo = null;
        setAddUserView(true);
        showGroupNotice();
        handleUnReadView();
        handleSecretChat();
    }

    private void handleUnReadView(){
        if(conversation!=null){
            if(conversation.unread_count>0){
                showUnreadMessageCountLabel(conversation.unread_count);
            }else{
                hideUnreadMessageCountLabel();
            }
            if(conversation.unread_mention_count>0){
                showUnreadMentionCountLabel(conversation.unread_mention_count);
            }else{
                hideUnreadMentionCountLabel();
            }
        }
    }

    private void showGroupNotice(){
        if(conversation!=null&&conversation.isGroup()){
            long last_read_inbox_message_id = conversation.last_read_inbox_message_id;
            TelegramManager.getTelegramManager().getGroupNotice(getContext(), conversation.id, new TgResultBlock<MessageInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, MessageInfo obj) {
                    if(obj!=null&&obj.id>last_read_inbox_message_id){
                        GroupPostDialog.show(getContext(),obj.textTypeContent);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
        }
    }

    private void setAddUserView(boolean isNeedRequestData){
        isNeedRefrshData = false;
        if(conversation==null){
            moshengLayout.setVisibility(View.GONE);
            return;
        }
        TelegramManager.getTelegramManager().updateChatInfoChatPermession(getContext(),conversation);
        if(!conversation.isGroup()&&!conversation.isMyFovChat()&&!getString(R.string.system_role_text).equals(conversationTitle)){
            UserInfo userInfo = UserInfo.getUserInfo(conversation.userId());
            if(isNeedRequestData){
                syncUserFullInfo();
                requestOrgUserInfo(userInfo);
            }
            boolean isBlockContact = !(conversation.permissions != null && !conversation.permissions.banWhisper);
            if(isBlockContact||(userInfo!=null&&userInfo.isDeleteAccount())){
                moshengLayout.setVisibility(View.GONE);
            }else{
                moshengLayout.setVisibility(View.VISIBLE);
                if (userInfo!=null&&userInfo.is_contact) {
                    moshengLayout.setVisibility(View.GONE);
                } else {
                    if (!canAddFriend()) {
                        moshengLayout.setVisibility(View.GONE);
                    }
                }
            }
        }else{
            moshengLayout.setVisibility(View.GONE);
        }

    }

    private boolean canAddFriend() {
        AppConfigInfo info = AppConfigInfo.getAppConfigInfo();
        if (info != null) {
            if (info.onlyWhiteAddFriend) {
                return orgUserInfo != null ? orgUserInfo.isInternal : false;
            }
        }
        return true;
    }

    private OrgUserInfo orgUserInfo;
    private void requestOrgUserInfo(UserInfo user) {
        if (user != null) {
            TelegramManager.getTelegramManager().requestOrgContactInfo(getContext(), user.id, new TgResultBlock<OrgUserInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, OrgUserInfo obj) {
                    if (obj != null) {
                        orgUserInfo = obj;
                        setAddUserView(false);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                }
            });
        }
    }

    private void reloadMessage() {

    }

    private void loadMoreOldMessages() {
        loadMoreOldMessages(-1L);
    }

    private void loadMoreOldMessages(Long focusMeeageId) {
        loadMoreOldMessages(focusMeeageId,false);
    }

    private void loadMoreOldMessages(Long focusMeeageId,boolean isClickQuote) {
        long fromMessageId = Long.MAX_VALUE;
        if (adapter.getMessages() != null && !adapter.getMessages().isEmpty()) {
            fromMessageId = adapter.getItem(0).message.id;
        }
        final boolean isContinueLoad;
        int limit;
        if(focusMeeageId>0&&(focusMeeageId-fromMessageId)>0){
            if((focusMeeageId-fromMessageId)>MAX_MESSAGE_LOAD_AROUND){
                limit = MAX_MESSAGE_LOAD_AROUND;
                isContinueLoad = true;
            }else{
                limit = (int)(focusMeeageId-fromMessageId);
                isContinueLoad = false;
            }
        }else{
            limit = MESSAGE_LOAD_AROUND;
            isContinueLoad = false;
        }
        TelegramManager.getTelegramManager().getRealChatMessageList(getContext(),conversation.id, fromMessageId, 0, limit, new TgResultBlock<List<MessageInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<MessageInfo> obj) {
                if(obj!=null&&obj.size()>0){
                    List<UiMessage> uiMessages = new ArrayList<>();
                    for(MessageInfo messageInfo:obj){
                        uiMessages.add(new UiMessage(messageInfo));
                    }
                    adapter.addMessagesAtHead(uiMessages);
                    adapter.notifyItemChanged(uiMessages.size());
                    if(focusMeeageId>0){
                        if(isContinueLoad){
                            loadMoreOldMessages(focusMeeageId,isClickQuote);
                        }else{
                            recyclerView.post(new Runnable() {
                                @Override
                                public void run() {
                                    scrollToMessagePositionById(focusMeeageId,isClickQuote);
                                }
                            });
                        }

                    }else{
                        recyclerView.post(new Runnable() {
                            @Override
                            public void run() {
                                recyclerView.smoothScrollBy(0, -DensityUtil.dp2px(80));
                            }
                        });
                    }

                }
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                swipeRefreshLayout.setRefreshing(false);
            }
        });

    }

    private void loadMessage(){
        if(conversation.unread_count>0&&conversation.last_read_inbox_message_id>0){
            loadMessage(conversation.last_read_inbox_message_id);
        }else{
            loadMessage(0);
        }
    }

    private void loadMessage(long focusMessageId) {
        MutableLiveData<List<UiMessage>> result = new MutableLiveData<>();
        innerRequestMessages(MESSAGE_LOAD_AROUND,new ArrayList<UiMessage>(),focusMessageId,result);
        result.observe(getViewLifecycleOwner(), uiMessages -> {
            swipeRefreshLayout.setRefreshing(false);

            AppConfigInfo configInfo = AppConfigInfo.getAppWithoutLoginConfigInfo();
            SuperGroupInfo super_groupInfo = messageViewModel.getSuperGroupInfo();
            TelegramManager.GroupMemberState state = null;
            if(super_groupInfo != null){
                state = super_groupInfo.status.getMemberState();
            }
            List<UiMessage> linmessages =  new ArrayList<>();
            for (int i = 0;i<uiMessages.size();i++) {
                UiMessage msg = uiMessages.get(i);
                if(msg.message.messageType ==  TelegramManager.MessageType.MessageType_Text_Screenshot){
                    if(configInfo==null||configInfo.enabled_screenshot_notification){
                        linmessages.add(msg);
                    }
                }else if(msg.message.content.type.equals("messageChatDeleteMember")){
                    if(configInfo==null||configInfo.shown_everyone_member_changes){
                        linmessages.add(msg);
                    }else{
                        if (state == TelegramManager.GroupMemberState.GroupMemberState_Administrator || state == TelegramManager.GroupMemberState.GroupMemberState_Creator) {
                            //管理展示
                            linmessages.add(msg);
                        }
                    }
                }else{
                    linmessages.add(msg);
                }
            }
            adapter.setMessages(linmessages);

            adapter.notifyDataSetChanged();

            if (adapter.getItemCount() > 1) {
                int initialMessagePosition;
                if (focusMessageId != 0) {
                    initialMessagePosition = adapter.getMessagePosition(focusMessageId)+1;
                    if (initialMessagePosition != -1&&initialMessagePosition<adapter.getItemCount()) {
                        recyclerView.scrollToPosition(initialMessagePosition);
                    }
                } else {
                    if(conversation.unread_count>0&&conversation.last_read_inbox_message_id>0){
                        if(adapter.getItemCount()>=conversation.unread_count){
                            recyclerView.scrollToPosition(adapter.getItemCount() -conversation.unread_count);
                        }else{
                            recyclerView.scrollToPosition(0);
                        }

                    }else{
                        moveToBottom = true;
                        recyclerView.scrollToPosition(adapter.getItemCount() - 1);
                    }
                }
            }
        });

    }

    private void innerRequestMessages(final int loadAroundNumber,final List<UiMessage> totalMessages,final long focusMessageId,final MutableLiveData<List<UiMessage>> result){
        long targetFocusMessageId;
        if(Common.isEmpty(totalMessages)){
            targetFocusMessageId = 0;
        }else{
            targetFocusMessageId = totalMessages.get(0).message.id;
        }
        TelegramManager.getTelegramManager().getRealChatMessageList(getContext(),conversation.id, targetFocusMessageId, 0, loadAroundNumber, new TgResultBlock<List<MessageInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<MessageInfo> obj) {
                if(obj!=null&&obj.size()>0){
                    ArrayList<UiMessage> messages = new ArrayList<>();
                    for(MessageInfo messageInfo:obj){
                        messages.add(new UiMessage(messageInfo));
                    }
                    totalMessages.addAll(0,messages);

                    if(focusMessageId>0&&!Common.isEmpty(totalMessages)&&totalMessages.get(0).message.id>focusMessageId){
                        int offset;
                        if(totalMessages.get(0).message.id - focusMessageId<MESSAGE_LOAD_AROUND){
                            offset = MESSAGE_LOAD_AROUND;
                        }else{
                            offset = MAX_MESSAGE_LOAD_AROUND;
                        }
                        innerRequestMessages(offset,totalMessages,focusMessageId,result);
                    }else{
                        result.postValue(totalMessages);
                    }
                }else{
                    result.postValue(totalMessages);
                }



            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                result.postValue(new ArrayList<UiMessage>());
            }
        });
    }

    @OnClick(R.id.unreadMentionCountView)
    void onUnreadMentionCountTextViewClick() {
        if(conversation == null){
            return;
        }
        int unread_mention_count = conversation.unread_mention_count;
        if(unread_mention_count<=0){
            hideUnreadMentionCountLabel();
            recyclerView.scrollToPosition(adapter.getItemCount() - 1);
            return;
        }
        List<Long> ids = new ArrayList<>();
        boolean isFind = false;
        int count = adapter.getItemCount();
        for(int i = 0;i<count;i++){
            UiMessage uiMessage = adapter.getItem(i);
            if(uiMessage!=null&&uiMessage.message!=null&&uiMessage.message.id>=conversation.last_read_inbox_message_id){
                ids.add(uiMessage.message.id);
            }
            if(uiMessage!=null&& uiMessage.message!=null
                    && uiMessage.message.id>=conversation.last_read_inbox_message_id
                    && uiMessage.message.content!=null
                    && uiMessage.message.content.text!=null
                    && !Common.isEmpty(uiMessage.message.content.text.entities)){
                recyclerView.scrollToPosition(i);
                break;
            }
        }
        TelegramManager.getTelegramManager().setMessagesReaded(conversation.id,ids);
        if(!isFind){
            hideUnreadMentionCountLabel();
        }
    }

    public void setReciveRead(MessageInfo messageInfo){
        if(messageInfo==null){
            return;
        }
        boolean isSetRead = false;
        if(conversation!=null){
            if(messageInfo.id>conversation.last_read_inbox_message_id){
                isSetRead = true;
            }
        }else{
            isSetRead = true;
        }
        if(isSetRead){
            List<Long> ids = new ArrayList<>();
            ids.add(messageInfo.id);
            TelegramManager.getTelegramManager().setMessagesReaded(messageInfo.chat_id,ids);
        }
    }

    @OnClick(R.id.unreadCountView)
    void onUnreadCountTextViewClick() {
        if(conversation == null){
            return;
        }
        List<Long> ids = new ArrayList<>();
        int count = adapter.getItemCount();
        for(int i = count-1;i>=0;i--){
            MessageInfo messageInfo = adapter.getItem(i).message;
            if(messageInfo!=null&&messageInfo.id>conversation.last_read_inbox_message_id){
                ids.add(messageInfo.id);
            }
        }
        TelegramManager.getTelegramManager().setMessagesReaded(conversation.id,ids);
        recyclerView.scrollToPosition(adapter.getItemCount() - 1);
    }

    @OnClick(R.id.pingbiUserBtn)
    void onPingbiUserBtnClick(){
        blockSwitchClick();
    }

    private void blockSwitchClick() {
        if (userFullInfo == null) {
            syncUserFullInfo();
            return;
        }
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        dialog.setTitle(R.string.dialog_title_tip).setMessage(userFullInfo.is_blocked ? getString(R.string.want_to_unblock_this_person) : getString(R.string.want_to_block_this_person));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        blockUser();
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void blockUser() {
        showProgress();
        TelegramManager.getTelegramManager().blockUser(getContext(), conversation.id, !userFullInfo.is_blocked, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                } else {
                    userFullInfo.is_blocked = !userFullInfo.is_blocked;
                    pingbiUserBtn.setText(userFullInfo.is_blocked?getString(R.string.person_has_been_blocked):getString(R.string.block_this_person));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void showProgress(){
        if(getActivity()!=null&&getActivity() instanceof BaseActivity){
            ((BaseActivity)getActivity()).showProgress();
        }
    }
    private void hideProgress(){
        if(getActivity()!=null&&getActivity() instanceof BaseActivity){
            ((BaseActivity)getActivity()).hideProgress();
        }
    }

    private void showErrorTip(String msg){
        if(getActivity()!=null&&getActivity() instanceof BaseActivity){
            ((BaseActivity)getActivity()).showErrorTip(msg);
        }
    }

    private void showWarnTip(String msg){
        if(getActivity()!=null&&getActivity() instanceof BaseActivity){
//            ((BaseActivity)getActivity()).showWarnTip(msg);
        }
    }

    @OnClick(R.id.addUserBtn)
    void onAddUserBtnClick(){
        if(conversation!=null&&!isGroupChat()){
            UserInfo userInfo = UserInfo.getUserInfo(conversation.userId());
            clickAdd(userInfo);
        }
    }
    private UserFullInfo userFullInfo;
    private void syncUserFullInfo(){
        if(conversation==null){
            return;
        }
        TelegramManager.getTelegramManager().requestContactFullInfo(getContext(), conversation.id, new TgResultBlock<UserFullInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserFullInfo obj) {
                if (obj != null) {
                    userFullInfo = obj;
                    pingbiUserBtn.setText(userFullInfo.is_blocked?getString(R.string.person_has_been_blocked):getString(R.string.block_this_person));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }

    private void clickAdd(UserInfo user) {//添加好友
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        dialog.setTitle(R.string.dialog_title_tip).setMessage(String.format(getString(R.string.want_to_add_somebody_friend), user.displayName()));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        doAddContact(user);
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void doAddContact(UserInfo user) {
        showProgress();
        TelegramManager.getTelegramManager().addContact(getContext(), user, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                } else {
                    moshengLayout.setVisibility(View.GONE);
                    showWarnTip(String.format(getString(R.string.somebody_added_friends), user.displayName()));
                    TelegramManager.getTelegramManager().sendBeFriendMessage(getContext(), user.id, new TgResultBlock<TgResponse>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {
                        }
                    });
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void showUnreadMessageCountLabel(int count) {
        unreadCountLinearLayout.setVisibility(View.VISIBLE);
        unreadCountView.setVisibility(View.VISIBLE);
        unreadCountTextView.setText(count + "");
    }

    private void hideUnreadMessageCountLabel() {
        unreadCountView.setVisibility(View.GONE);
    }

    private void showUnreadMentionCountLabel(int count) {
        unreadCountLinearLayout.setVisibility(View.VISIBLE);
        unreadMentionCountView.setVisibility(View.VISIBLE);
        unreadMentionCountTextView.setText(count + "");
    }

    private void hideUnreadMentionCountLabel() {
        unreadMentionCountView.setVisibility(View.GONE);
    }

    private void quitChatRoom() {

    }

    private void setTitle() {
        if (!TextUtils.isEmpty(conversationTitle)) {
            setActivityTitle(conversationTitle);
        }
        String subTitle = null;
        if(conversation!=null&&!conversation.isGroup()){
            UserInfo userInfo = UserInfo.getUserInfo(conversation.userId());
            if(userInfo!=null){
                subTitle = userInfo.getUserStatusLable();
                if(userInfo.isDeleteAccount()){
                    ban_SendMessage(getString(R.string.already_clean_account));
                }else if(!userInfo.canSendMsg()){
                    ban_SendMessage(getString(R.string.restrict_stranger_chat));
                }else{
                    canSendMessage();
                }
            }
        }
        setActivitySubTitle(subTitle);
    }

    private void setActivitySubTitle(String subTitle){
        if(getActivity()!=null&&getActivity() instanceof ChatActivity){
            ((ChatActivity)getActivity()).setSubTitle(subTitle);
        }
    }

    public void deleteMessages(OnDeleteDialogListener listener){
        if(conversation==null||listener==null){
            return;
        }
        List<String> data = new ArrayList<>();
        if(conversation.isGroup()||conversation.userId()== UserInfo.getUserInfo().id){
            data.add(getString(R.string.only_for_me_to_delete));
        }else{
            UserInfo userInfo = UserInfo.getUserInfo(conversation.userId());
            data.add(String.format(getString(R.string.only_for_both_to_delete),userInfo!=null?userInfo.displayName():getString(R.string.other_side)));
            data.add(getString(R.string.only_for_me_to_delete));
        }
        ChooseListDialog.showChooseListDialog(getContext(), data, -1, new OnChooseListListener() {
            @Override
            public void onChoose(int position, String value) {
                if(conversation.isGroup()||conversation.userId()== UserInfo.getUserInfo().id){
                    listener.onDeleteRevoke(true);
                }else{
                    listener.onDeleteRevoke(position==1);
                }
            }
        });
    }

    private void setActivityInputSubTitle(String subTitle){
        if(getActivity()!=null&&getActivity() instanceof ChatActivity){
            ((ChatActivity)getActivity()).setInputSubTitle(subTitle);
        }
    }

    private void setActivityTitle(String title) {
        Activity activity = getActivity();
        if (activity != null) {
            activity.setTitle(title);
        }
    }

    @OnTouch({R.id.contentLayout, R.id.msgRecyclerView})
    boolean onTouch(View view, MotionEvent event) {
//        if (event.getAction() == MotionEvent.ACTION_DOWN && inputPanel.extension.canHideOnScroll()) {
//            inputPanel.collapse();
//        }
        inputPanel.closeConversationInputPanel();
        return false;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode >= ConversationExtension.REQUEST_CODE_MIN) {
            boolean result = inputPanel.extension.onActivityResult(requestCode, resultCode, data);
            if (result) {
                return;
            }
            Log.d(TAG, "extension can not handle " + requestCode);
        }
        if (resultCode == Activity.RESULT_OK) {

        }
    }



    @Override
    public void onPause() {
        super.onPause();
        isNeedRefrshData = true;
        inputPanel.onActivityPause();
        messageViewModel.stopPlayAudio();
    }

    public boolean isGroupChat(){
        if(conversation==null){
            return false;
        }
        return conversation.isGroup();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (conversation == null) {
            return;
        }

        if (conversation.isGroup()) {
            quitChatRoom();
        }
        messageViewModel.messageLiveData().removeObserver(messageLiveDataObserver);
        messageViewModel.messageUpdateLiveData().removeObserver(messageUpdateLiveDatObserver);
        messageViewModel.mediaUpdateLiveData().removeObserver(mediaUploadedLiveDataObserver);
        messageViewModel.groupInfoLiveData().removeObserver(groupInfoObserver);
        messageViewModel.groupSubTitleLiveData().removeObserver(groupSubTitleObserver);
        inputPanel.onDestroy();
    }

    private void updateUser(UserInfo userInfo){
        Observable.create(new ObservableOnSubscribe<DiffUtil.DiffResult>() {
                    @Override
                    public void subscribe(ObservableEmitter<DiffUtil.DiffResult> e) {
                        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new AvatarDiffCallBack(adapter.getMessages(), adapter.getMessages()), false);
                        e.onNext(diffResult);
                    }
                }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DiffUtil.DiffResult>() {
                    @Override
                    public void accept(DiffUtil.DiffResult diffResult) {
                        diffResult.dispatchUpdatesTo(adapter);
                    }
                });
    }

    public void onTgEvent(final TgEvent tg_event){
        if(tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_UpdateContactInfo||tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_AddNewContactInfo){
            setTitle();
        }
        switch (tg_event.event) {
            case EUser_Td_Contact_Photo_Ok:
            case EUser_Td_UpdateContactInfo:
                if((tg_event.data instanceof UserInfo)){
                    UserInfo userInfo = (UserInfo)tg_event.data;
                    updateUser(userInfo);
                }
                break;
            case EUser_Td_Message_Photo_Ok:
            case EUser_Td_Message_Video_Ok:
            case EUser_Td_Message_Audio_Ok:
            case EUser_Td_Message_Voice_Ok:
            case EUser_Td_Message_Preview_Photo_Ok:
            case EUser_Td_Message_Document_Ok:
            case EUser_Td_Message_Animation_Ok:
                if(tg_event.data instanceof FileTaskInfo&&tg_event.dataEx instanceof FileInfo){
                    FileInfo fileInfo = (FileInfo) tg_event.dataEx;
                    String ids = ((FileTaskInfo)tg_event.data).id;
                    if(!TextUtils.isEmpty(ids)&&ids.contains("_")){
                        String[] idArray = ids.split("_");
                        if(idArray.length >= 2){
                            if(idArray[0].equals(String.valueOf(conversation.id))){
                                for(int i = 0; i<adapter.getItemCount();i++){
                                    MessageInfo message = adapter.getItem(i).message;
                                    adapter.getItem(i).isDownloading = false;
                                    if(message.id == Long.parseLong(idArray[1])){
                                        switch (tg_event.event) {
                                            case EUser_Td_Message_Photo_Ok:
                                                message.updateMessagePhotoFile(fileInfo);
                                                break;
                                            case EUser_Td_Message_Preview_Photo_Ok:
                                                message.updatePreviewPhotoFile(fileInfo);
                                                break;
                                            case EUser_Td_Message_Video_Ok:
                                                message.updateVideoFile(fileInfo);
                                                break;
                                            case EUser_Td_Message_Document_Ok:
                                                message.updateDocumentFile(fileInfo);
                                                break;
                                            case EUser_Td_Message_Animation_Ok:
                                                message.updateAnimationFile(fileInfo);
                                                break;
                                            case EUser_Td_Message_Voice_Ok:
                                                message.updateVoiceFile(fileInfo);
                                                break;
                                            default:
                                                message.updateAudioFile(fileInfo);
                                                break;

                                        }
                                        if(tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_Message_Video_Ok){
                                            if(lastPlayHolder==null){
                                                adapter.notifyItemChanged(i,100);
                                            }
                                        }else{
                                            adapter.notifyItemChanged(i,100);
                                        }
                                        break;
                                    }
                                }
                            }
                        }

                        if(lastPlayHolder!=null){
                            lastPlayHolder.playerContaniner.getLocalVisibleRect(rect);
                            int height = lastPlayHolder.playerContaniner.getHeight();
                            if (rect.top == 0 && rect.bottom == height) {
                                startPlay(lastPlayHolder);
                            }
                        }


                    }
                }
                break;
            case EUser_Td_Chat_New_Message:
                if(tg_event.data!=null&&tg_event.data instanceof MessageInfo){
                    MessageInfo messageInfo = (MessageInfo)tg_event.data;
                    if(isMessageInCurrentConversation(messageInfo.chat_id)){
                        if(messageInfo.messageType== TelegramManager.MessageType.MessageType_Text_Refund_Tm
                                ||messageInfo.messageType== TelegramManager.MessageType.MessageType_Text_Got_Tm){
                            if(messageInfo.tmInfo!=null){
                                adapter.notifyMesssageByRemittedId(messageInfo.tmInfo.remittanceId);
                            }
                        }
                        appendNewMessage(new UiMessage(messageInfo));
                    }
                }
                break;
            case EUser_Td_Chat_Pin_Message:
                if(tg_event.data!=null&&tg_event.data instanceof PinMessage){
                    PinMessage pinMessage = (PinMessage)tg_event.data;
                    if(isMessageInCurrentConversation(pinMessage.chat_id)){
                        String content = null;
                        if(pinMessage.pinned_message_id>0){
                            UiMessage msg = adapter.findMsgById(pinMessage.pinned_message_id);
                            if(msg!=null){
                                content = msg.message.textTypeContent;
                            }
                            if(!TextUtils.isEmpty(content)){
                                content = content.replace("@所有人 ","");
                            }
                        }
                        if(!TextUtils.isEmpty(content)&&!isNeedRefrshData){
                            GroupPostDialog.show(getContext(),content);
                        }
                    }
                }
                break;
            case EUser_Td_Chat_Send_Message_Success:
            case EUser_Td_Chat_Send_Message_Fail:
                if(tg_event.data!=null&&tg_event.data instanceof MessageInfo&&tg_event.dataEx instanceof Long){
                    MessageInfo messageInfo = (MessageInfo)tg_event.data;
                    if(isMessageInCurrentConversation(messageInfo.chat_id)){
                        UiMessage message = adapter.findMsgById((Long) tg_event.dataEx);
                        if(message!=null){
                            message.message.id = messageInfo.id;
                            adapter.updateMessage(new UiMessage(messageInfo));

                        }else{
                            recyclerView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    UiMessage message = adapter.findMsgById((Long) tg_event.dataEx);
                                    if(message!=null){
                                        message.message.id = messageInfo.id;
                                        messageViewModel.messageLiveData().postValue(new UiMessage(messageInfo));
                                    }
                                }
                            },600);
                        }

                    }
                }
                break;
            case ECircle_Send_Blog_Progressing:
                if(tg_event.data!=null&&tg_event.data instanceof FileInfo){
                    FileInfo fileInfo = (FileInfo) tg_event.data;
                    if(fileInfo.remote.is_uploading_completed){
                        return;
                    }
                    for(int i = adapter.getItemCount()-1; i>=0;i--) {
                        MessageInfo message = adapter.getItem(i).message;
                        if(message.updateFileInfo(fileInfo)){
                            adapter.notifyItemChanged(i,100);
                            break;
                        }
                    }
                }
                break;
            case EUser_Td_Chat_Delete_Message:
                if(tg_event.data!=null&&tg_event.data instanceof DeleteMessagesInfo){
                    DeleteMessagesInfo messageInfo = (DeleteMessagesInfo)tg_event.data;
                    if(isMessageInCurrentConversation(messageInfo.chat_id)&&messageInfo.isRealDelete()&&messageInfo.message_ids!=null&&messageInfo.message_ids.size()>0){
                        for (Long msgId:messageInfo.message_ids){
                            adapter.removeMessageById(msgId);
                        }
                    }
                }
                break;
            case EUser_Td_Message_Total_Unread_Changed:
                if(tg_event.data!=null&&tg_event.data instanceof Integer&&getActivity()!=null&&getActivity() instanceof ChatActivity){
                    ((ChatActivity)getActivity()).setChatUnReadNum((Integer) tg_event.data);
                    if(conversation!=null){
                        ChatInfo chatInfo = TelegramManager.getTelegramManager().getTgData().chatInfo(conversation.id);
                        if(chatInfo!=null){
                            conversation.unread_count = chatInfo.unread_count;
                            conversation.unread_mention_count = chatInfo.unread_mention_count;
                            conversation.last_read_inbox_message_id = chatInfo.last_read_inbox_message_id;
                            handleUnReadView();
                        }
                    }
                }
                break;
            case EUser_Td_Chat_OutMessage_Readed:
                if(tg_event.data!=null&&tg_event.data instanceof ChatInfo){
                    ChatInfo chatInfo = (ChatInfo)tg_event.data;
                    if(isMessageInCurrentConversation(chatInfo.id)){
                        chatInfo.permissions = conversation.permissions;
                        conversation = chatInfo;
                        adapter.notifyDataSetChanged();

                        handleUnReadView();
                    }
                }
                break;
            case EUser_Td_Chat_Title_Changed:
                if(tg_event.data!=null&&(tg_event.data instanceof ChatInfo)){
                    ChatInfo chatInfo = (ChatInfo)tg_event.data;
                    if(isMessageInCurrentConversation(chatInfo.id)){
                        chatInfo.permissions = conversation.permissions;
                        conversation = chatInfo;
                        reloadCenterTitle();
                        setTitle();
                        setRightTitle(conversation.isGroup()?conversation.getGroupCount(messageViewModel.getSuperGroupInfo()):"");
                    }
                }
                break;
            case EUser_Td_Group_Super_Info_Changed:
                if(tg_event.data!=null&&tg_event.data instanceof SuperGroupInfo){
                    SuperGroupInfo groupInfo = (SuperGroupInfo)tg_event.data;
                    if(conversation!=null&&conversation.superGroupId() == groupInfo.id){
                        messageViewModel.setSuperGroupInfo(groupInfo);
                        messageViewModel.loadGroupMembers(getContext(),conversation);
                    }
                }
                break;
            case EUser_Td_Chat_Permissions_Changed:
                if(tg_event.data!=null&&tg_event.data instanceof ChatInfo){
                    ChatInfo chatInfo = (ChatInfo)tg_event.data;
                    if(conversation!=null&&conversation.id == chatInfo.id){
                        ChatPermissions chatPermissions = conversation.permissions;
                        if(chatPermissions!=null&&chatInfo.permissions!=null){
                            chatPermissions.can_send_messages = chatInfo.permissions.can_send_messages;
                            chatPermissions.can_send_media_messages = chatInfo.permissions.can_send_media_messages;
                            chatPermissions.can_send_polls = chatInfo.permissions.can_send_polls;
                            chatPermissions.can_send_other_messages = chatInfo.permissions.can_send_other_messages;
                            chatPermissions.can_add_web_page_previews = chatInfo.permissions.can_add_web_page_previews;
                            chatPermissions.can_change_info = chatInfo.permissions.can_change_info;
                            chatPermissions.can_invite_users = chatInfo.permissions.can_invite_users;
                            chatPermissions.can_pin_messages = chatInfo.permissions.can_pin_messages;
                        }
                        if(messageViewModel.getSuperGroupInfo()!=null){
                            messageViewModel.groupInfoLiveData().postValue(messageViewModel.getSuperGroupInfo());
                        }
                    }
                }
                break;
            case EUser_Td_Group_Permission_Change:
                if(tg_event.data!=null&&tg_event.data instanceof GroupManagePermissionInfo){
                    GroupManagePermissionInfo permissionInfo = (GroupManagePermissionInfo)tg_event.data;
                    if(conversation!=null&&conversation.id == permissionInfo.chatId){
                        ChatPermissions chatPermissions = conversation.permissions;
                        if(chatPermissions!=null){
                            chatPermissions.banSendKeyword = permissionInfo.banSendKeyword;
                            chatPermissions.banSendQRcode = permissionInfo.banSendQRcode;
                            chatPermissions.banSendWebLink = permissionInfo.banSendWebLink;
                            chatPermissions.banWhisper = permissionInfo.banWhisper;
                        }
                    }
                }
                break;
            case EUser_Td_Group_Keywords_Change:
                if(tg_event.data!=null&&tg_event.data instanceof GroupManagePermissionInfo){
                    GroupManagePermissionInfo permissionInfo = (GroupManagePermissionInfo)tg_event.data;
                    if(conversation!=null&&conversation.id == permissionInfo.chatId){
                        ChatPermissions chatPermissions = conversation.permissions;
                        if(chatPermissions!=null){
                            chatPermissions.keywords = permissionInfo.keywords;
                        }
                    }
                }
                break;
            case EUser_Td_Group_Super_Full_Info_Changed:
                if(tg_event.dataEx!=null&&tg_event.dataEx instanceof Long){
                    Long groupId = (Long) tg_event.dataEx;
                    if(conversation!=null&&conversation.superGroupId() == groupId&&messageViewModel!=null){
                        messageViewModel.loadGroupMembers(getContext(),conversation);
                    }
                }
                break;
            case EUser_Td_Chat_At_Someone:
            case EUser_Td_Chat_Dm_At_Someone:
                if(tg_event.data!=null&&tg_event.data instanceof UserInfo&&tg_event.dataEx!=null&&tg_event.dataEx instanceof Long){
                    Long chatId = (Long) tg_event.dataEx;
                    if(isMessageInCurrentConversation(chatId)){
                        UserInfo userInfo = (UserInfo)tg_event.data;
                        int position = inputPanel.editText.getSelectionEnd();
                        SpannableString spannableString;
                        int endPosition;
                        if(tg_event.event== TelegramManager.EUser_TgEvent.EUser_Td_Chat_Dm_At_Someone){
                            String text = inputPanel.editText.getText().toString();
                            String dmText = !TextUtils.isEmpty(text)&&text.length()>= Constants.DM_TEXT_LENGTH?text.substring(text.length()-Constants.DM_TEXT_LENGTH,text.length()): Constants.DM_TEXT;
                            spannableString = mentionSpannable(userInfo,dmText);
                            position = position > 0 ? position - Constants.DM_TEXT_LENGTH : 0;
                            endPosition = position+Constants.DM_TEXT_LENGTH;
                        }else{
                            spannableString = mentionSpannable(userInfo);
                            position = position > 0 ? position - 1 : 0;
                            endPosition = position+1;
                        }
                        inputPanel.editText.getEditableText().replace(position, endPosition, spannableString);
                    }
                }
                break;
            case EUser_Td_Chat_Bg_Changed:
                if(tg_event.data!=null&&tg_event.data instanceof Long){
                    Long chatId = (Long) tg_event.data;
                    if(isMessageInCurrentConversation(chatId)){
                        setChatBg();
                    }
                }
                break;
            case EUser_Td_Chat_Typing:
                if(tg_event.data!=null&&tg_event.data instanceof UpdateChatActionInfo){
                    UpdateChatActionInfo chatActionInfo = (UpdateChatActionInfo)tg_event.data;
                    if(isMessageInCurrentConversation(chatActionInfo.chat_id)){
                        startShowSubTitle(chatActionInfo);

                    }
                }
                break;
            case EUser_Td_Chat_Online_Count:
                if(tg_event.data!=null&&tg_event.data instanceof ChatOnlineMemberCountInfo){
                    ChatOnlineMemberCountInfo countInfo = (ChatOnlineMemberCountInfo) tg_event.data;
                    if(isMessageInCurrentConversation(countInfo.chat_id)){
                        groupSubTitleObserver.onChanged(new Pair<Long, String>(conversation.superGroupId(),String.format(getString(R.string.number_person_online),countInfo.online_member_count)));
                    }
                }
                break;
            case EUser_Td_Chat_Update_Secret:
                if(tg_event.data!=null&&tg_event.data instanceof SecretChatInfo){
                    SecretChatInfo secretChatInfo = (SecretChatInfo) tg_event.data;
                    if(conversation!=null&&conversation.isSecretChat()&&conversation.secretChatId() == secretChatInfo.id){
                        updateSecretChatInfo(secretChatInfo);
                    }
                }
                break;
            case EUser_Td_Group_User_Nick_Name:
                if(tg_event.data!=null&&tg_event.data instanceof GroupUserInfo) {
                    GroupUserInfo groupUserInfo = (GroupUserInfo) tg_event.data;
                    if(isMessageInCurrentConversation(groupUserInfo.chatId)){
                        messageViewModel.putGroupNickName(groupUserInfo.userId,groupUserInfo.nickname);
                        for(int i = 0; i<adapter.getItemCount();i++) {
                            MessageInfo message = adapter.getItem(i).message;
                            if(message.sender_user_id() == groupUserInfo.userId){
                                adapter.notifyItemChanged(i,Constants.Notify_User_Name_Type);
                            }
                        }
                    }
                }
                break;
            case EUser_Td_Chat_Update_Reaction:
                if(tg_event.data!=null&&tg_event.data instanceof MessageReactionInfo) {
                    MessageReactionInfo reactionInfo = (MessageReactionInfo) tg_event.data;
                    if(Common.isEmpty(reactionInfo.reactionList)){
                        return;
                    }
                    MessageReaction reaction = reactionInfo.reactionList.get(0);
                    if(isMessageInCurrentConversation(reactionInfo.getChatId())){
                        for(int i = 0; i<adapter.getItemCount();i++) {
                            UiMessage message = adapter.getItem(i);
                            if(message.message.id == reactionInfo.messageId){
                                message.isRequestMessageReactions = true;
                                if(reaction.reactionId == 0){
                                    if(!Common.isEmpty(message.reactions)){
                                        List<MessageReaction> reactions = message.reactions;
                                        MessageReaction preReaction = message.haveReactionByUserId(reaction.userId);
                                        if(preReaction != null){
                                            preReaction.removeUserId(reaction.userId);
                                            if(Common.isEmpty(preReaction.userIds)){
                                                reactions.remove(preReaction);
                                            }
                                        }
                                    }
                                }else{
                                    if(!Common.isEmpty(message.reactions)){
                                        List<MessageReaction> reactions = message.reactions;
                                        MessageReaction preReaction = message.haveReactionByUserId(reaction.userId);
                                        if(preReaction != null){
                                            preReaction.removeUserId(reaction.userId);
                                            if(Common.isEmpty(preReaction.userIds)){
                                                reactions.remove(preReaction);
                                            }
                                        }
                                        int index = reactions.indexOf(reaction);
                                        if(index>=0){
                                            reactions.get(index).appendUserId(reaction.userId);
                                        }else{
                                            reaction.appendUserId(reaction.userId);
                                            reactions.add(reaction);
                                        }
                                    }else{
                                        List<MessageReaction> reactions = new ArrayList<>();
                                        reaction.appendUserId(reaction.userId);
                                        reactions.add(reaction);
                                        message.reactions = reactions;
                                    }
                                }
                                adapter.notifyItemChanged(i,Constants.Notify_Message_Reaction);
                                break;
                            }
                        }
                    }
                }
                break;
            case  EUser_Td_Chat_Send_Reaction:
                if(tg_event.data!=null&&tg_event.data instanceof UiMessage&&tg_event.dataEx!=null&&tg_event.dataEx instanceof Integer) {
                    sendReaction((UiMessage) tg_event.data,(int)tg_event.dataEx);
                }
                break;
        }
    }

    private void startShowSubTitle(UpdateChatActionInfo chatActionInfo){
        HideRunable hideRunable = mHideRunables.get(chatActionInfo.user_id);
        if(hideRunable==null){
            hideRunable = new HideRunable(this,chatActionInfo);
            mHideRunables.put(chatActionInfo.user_id,hideRunable);
        }else{
            inputPanel.removeCallbacks(hideRunable);
        }
        if(mHideRunables!=null&&mHideRunables.size()>0){
            if(conversation!=null&&conversation.isSuperGroup()){
                StringBuilder stringBuilder = new StringBuilder("...");
                for (Long o : mHideRunables.keySet()) {
                    UserInfo userInfo = UserInfo.getUserInfo(o);
                    if(userInfo!=null){
                        stringBuilder.append(userInfo.displayName());
                        stringBuilder.append(",");
                    }
                }
                if(stringBuilder.length()>3){
                    stringBuilder.deleteCharAt(stringBuilder.length()-1);
                }
                setActivityInputSubTitle(stringBuilder.toString());
            }else{
                setActivityInputSubTitle(getString(R.string.typing_text));
            }
        }else{
            setActivityInputSubTitle(null);
        }

        inputPanel.postDelayed(hideRunable,5000);
    }

    private HashMap<Long,HideRunable> mHideRunables = new HashMap<>();

    private void hideChangeTitle(UpdateChatActionInfo chatActionInfo){
        if(mHideRunables.containsKey(chatActionInfo.user_id)){
            mHideRunables.remove(chatActionInfo.user_id);
        }
        if(mHideRunables==null||mHideRunables.size()==0){
            setActivityInputSubTitle(null);
        }else{
            if(conversation!=null&&conversation.isSuperGroup()){
                StringBuilder stringBuilder = new StringBuilder("...");
                for (Long o : mHideRunables.keySet()) {
                    UserInfo userInfo = UserInfo.getUserInfo(o);
                    if(userInfo!=null){
                        stringBuilder.append(userInfo.displayName());
                        stringBuilder.append(",");
                    }
                }
                if(stringBuilder.length()>3){
                    stringBuilder.deleteCharAt(stringBuilder.length()-1);
                }
                setActivityInputSubTitle(stringBuilder.toString());
            }else{
                setActivityInputSubTitle(null);
            }
        }

    }


    public void onRemiitedClick(long remittanceId){
        showProgress();
        TelegramManager.getTelegramManager().queryTransferMoney(getContext(), remittanceId, new TgResultBlock<RemittanceDetailInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, RemittanceDetailInfo obj) {
                hideProgress();
                if(obj!=null){
                    obj.remittanceId = remittanceId;
                    TransferMoneyDetailActivity.start(getContext(),obj);
                }else{
                    ToastUtils.showShort(getString(R.string.request_error));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                ToastUtils.showShort(getString(R.string.request_error));
            }
        });
    }


    public void resendMessage(MessageInfo message) {
        messageViewModel.resendMessage(conversation,message);
    }

    private static class HideRunable implements Runnable{
        private WeakReference<ConversationFragment> fragmentWeakReference;
        private UpdateChatActionInfo mChatActionInfo;
        public HideRunable(ConversationFragment fragment,UpdateChatActionInfo chatActionInfo) {
            fragmentWeakReference = new WeakReference<ConversationFragment>(fragment);
            mChatActionInfo = chatActionInfo;
        }

        @Override
        public void run() {
            if(fragmentWeakReference!=null
                    &&fragmentWeakReference.get()!=null
                    &&fragmentWeakReference.get().getActivity()!=null
                    &&!fragmentWeakReference.get().getActivity().isDestroyed()){
                fragmentWeakReference.get().hideChangeTitle(mChatActionInfo);
            }
        }
    }


    boolean onBackPressed() {
        boolean consumed = true;
        if (rootLinearLayout.getCurrentInput() != null) {
            rootLinearLayout.hideAttachedInput(true);
            inputPanel.closeConversationInputPanel();
        } else if (multiMessageActionContainerLinearLayout.getVisibility() == View.VISIBLE) {
            toggleConversationMode();
        } else {
            consumed = false;
        }
        return consumed;
    }

    private void setRightTitle(String value){
        if(getActivity()!=null&&getActivity() instanceof ChatActivity){
            ((ChatActivity)getActivity()).setRightTitle(value);
        }
    }

    @Override
    public void onKeyboardShown() {
        inputPanel.onKeyboardShown();
        recyclerView.scrollToPosition(adapter.getItemCount() - 1);
    }

    @Override
    public void onKeyboardHidden() {
        inputPanel.onKeyboardHidden();
    }

    private void loadMoreNewMessages() {
        loadingNewMessage = true;
        adapter.showLoadingNewMessageProgressBar();

    }


    private Runnable resetConversationTitleRunnable = this::resetConversationTitle;

    private void resetConversationTitle() {
        if (getActivity() == null || getActivity().isFinishing()) {
            return;
        }
        if (!TextUtils.equals(conversationTitle, getActivity().getTitle())) {
            setActivityTitle(conversationTitle);
            handler.removeCallbacks(resetConversationTitleRunnable);
        }
    }

    @Override
    public void onInputPanelExpanded() {
        recyclerView.scrollToPosition(adapter.getItemCount() - 1);
    }

    @Override
    public void onInputPanelCollapsed() {
        // do nothing
    }

    public void toggleMultiMessageMode(UiMessage message) {
        inputPanel.setVisibility(View.GONE);
        message.isChecked = true;
        adapter.setMode(ConversationMessageAdapter.MODE_CHECKABLE);
        adapter.notifyDataSetChanged();
        multiMessageActionContainerLinearLayout.setVisibility(View.VISIBLE);
        setupMultiMessageAction();
        if(getActivity() != null && getActivity() instanceof ChatActivity){
            ((ChatActivity)getActivity()).changeCancleBtnVisiable(true);
        }
    }

    public void favMessageMode(List<UiMessage> messages) {
        if(messages!=null&&messages.size()>0){
            List<MessageInfo> messageInfos = new ArrayList<>();
            for(UiMessage message:messages){
                messageInfos.add(message.message);
            }
            TelegramManager.getTelegramManager().createPrivateChat(getContext(), UserInfo.getUserInfo().id, new TgResultBlock<ChatInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                    if (obj != null) {
                        TelegramManager.getTelegramManager().forwardMessages(getContext(),obj.id,messageInfos);
                        ToastUtils.showShort(getString(R.string.collected_text));
                    }else{
                        ToastUtils.showShort(getString(R.string.request_error));
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    ToastUtils.showShort(getString(R.string.request_error));
                }
            });
        }
    }

    public void toggleConversationMode() {
        inputPanel.setVisibility(View.VISIBLE);
        multiMessageActionContainerLinearLayout.setVisibility(View.GONE);
        adapter.setMode(ConversationMessageAdapter.MODE_NORMAL);
        adapter.clearMessageCheckStatus();
        adapter.notifyDataSetChanged();
        if(getActivity() != null && getActivity() instanceof ChatActivity){
            ((ChatActivity)getActivity()).changeCancleBtnVisiable(false);
        }
    }

    public void toggleToCall(){
        if(conversation!=null&&!conversation.isGroup()){
            UserInfo userInfo = UserInfo.getUserInfo(conversation.userId());
            if(userInfo!=null){
                CallManager.startC2CNewCall(getActivity(),userInfo);
            }
        }
    }

    public void sendScreenshot(){
        if(conversation!=null){
            TelegramManager.getTelegramManager().sendScreenshotMessage(getContext(), conversation.id, new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {

                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
        }
    }

    public void setInputText(String text) {
        inputPanel.setInputText(text);
    }

    private void setupMultiMessageAction() {
        multiMessageActionContainerLinearLayout.removeAllViews();
        List<MultiMessageAction> actions = MultiMessageActionManager.getInstance().getConversationActions(conversation);
        int width = getResources().getDisplayMetrics().widthPixels;
        for (MultiMessageAction action : actions) {
            action.onBind(this, conversation);
            ImageView imageView = new ImageView(getActivity());
            imageView.setTag(action);
            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            imageView.setImageResource(action.iconResId());
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width / actions.size(), width /2/ actions.size());
            multiMessageActionContainerLinearLayout.addView(imageView, layoutParams);
            ViewGroup.LayoutParams p = imageView.getLayoutParams();
            p.height = 60;
            imageView.requestLayout();

            imageView.setOnClickListener(v -> {
                List<UiMessage> checkedMessages = adapter.getCheckedMessages();
                if(checkedMessages==null||checkedMessages.size()==0){
                    ToastUtils.showShort(getString(R.string.select_message));
                }else{
                    if (action.confirm()) {
                        new MaterialDialog.Builder(getActivity()).content(action.confirmPrompt(getActivity()))
                                .negativeText(getString(R.string.cancel))
                                .positiveText(getString(R.string.ok_text))
                                .onPositive((dialog, which) -> {
                                    action.onClick(checkedMessages);
                                    toggleConversationMode();
                                })
                                .build()
                                .show();

                    } else {
                        action.onClick(checkedMessages);
                        toggleConversationMode();
                    }
                }

            });
        }
        checkMultiEnable(adapter.getCheckedMessages());
    }

    @Override
    public void onMessageCheck(UiMessage message, boolean checked) {
        List<UiMessage> checkedMessages = adapter.getCheckedMessages();
        setAllClickableChildViewState(multiMessageActionContainerLinearLayout, checkedMessages.size() > 0);
        checkMultiEnable(checkedMessages);
    }

    private void checkMultiEnable(List<UiMessage> checkedMessages){
        int childCount = multiMessageActionContainerLinearLayout.getChildCount();
        if(multiMessageActionContainerLinearLayout.getVisibility() == View.VISIBLE&&childCount>0){
            for(int i = 0;i<childCount;i++){
                View view = multiMessageActionContainerLinearLayout.getChildAt(i);
                Object tag = view.getTag();
                if(tag!=null&&tag instanceof MultiMessageAction){
                    view.setEnabled(((MultiMessageAction)tag).checkActionEnable(checkedMessages));
                }
            }
        }
    }

    private void setAllClickableChildViewState(View view, boolean enable) {
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                setAllClickableChildViewState(((ViewGroup) view).getChildAt(i), enable);
            }
        }
        if (view.isClickable()) {
            view.setEnabled(enable);
        }
    }

    public void onUserNameClick(String userName){
        if(TextUtils.isEmpty(userName)){
            return;
        }
        List<GroupMemberInfo> memberInfos = messageViewModel.getGroupMembers();
        if(memberInfos!=null&&memberInfos.size()>0){
            for(GroupMemberInfo memberInfo:memberInfos){
                if( userName.equals(UserInfo.userDisplayName(memberInfo.user_id))){
                    UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(memberInfo.user_id);
                    if(user!=null){
                        onPortraitClick(user);
                    }
                    return;
                }
            }
        }
    }

    @Override
    public void onPortraitClick(UserInfo user) {
        if (user == null) return;
        if (user.id == UserInfo.getUserInfo().id) {
            ((ChatActivity)getActivity()).goProfileActivity();
        } else {
//            SuperGroupInfo super_groupInfo = messageViewModel.getSuperGroupInfo();
//            if (super_groupInfo != null && super_groupInfo.status != null) {
//                TelegramManager.GroupMemberState state = super_groupInfo.status.getMemberState();
//                if (state == TelegramManager.GroupMemberState.GroupMemberState_Administrator || state == TelegramManager.GroupMemberState.GroupMemberState_Creator) {
//                    ContactDetailActivity.start(getActivity(), user, conversation.id, true);
//                } else {
//                    //群组聊天列表 点击成员头像 20220803
//                    ContactDetailActivity.start(getActivity(), user, !(conversation.permissions != null && !conversation.permissions.banWhisper));
//                }
//            } else {
//                ContactDetailActivity.start(getActivity(), user, !(conversation.permissions != null && !conversation.permissions.banWhisper));
//            }
            boolean blockContact = !(conversation.permissions != null && !conversation.permissions.banWhisper);
            new XPopup.Builder(getActivity())
                    .hasShadowBg(true)
                    .isDestroyOnDismiss(true)
                    .dismissOnTouchOutside(true)
                    .borderRadius(10)
                    .atView(recyclerView)
                    .asCustom(new ChatUserDialog(getContext(), user,blockContact, new ChatUserDialog.OnItemClickListner() {
                        @Override
                        public void clickPostion(int postion, ChatInfo chatInfo) {

                        }
                    })).show();

        }
    }

    public boolean canDm(){
        if(conversation!=null&&conversation.isSuperGroup()){
            SuperGroupInfo super_groupInfo = messageViewModel.getSuperGroupInfo();
            if (super_groupInfo != null && super_groupInfo.status != null) {
                TelegramManager.GroupMemberState state = super_groupInfo.status.getMemberState();
                if (state == TelegramManager.GroupMemberState.GroupMemberState_Administrator || state == TelegramManager.GroupMemberState.GroupMemberState_Creator) {
                    return true;
                }
            }
            return conversation.permissions != null && !conversation.permissions.banWhisper;
        }
        return false;
    }


    @Override
    public void onPortraitLongClick(View view,final UserInfo userInfo) {
        if(userInfo==null||userInfo.id == UserInfo.getUserInfo().id){
            return;
        }
        if(messageViewModel!=null&&messageViewModel.getSuperGroupInfo()!=null){
            SuperGroupInfo superGroupInfo = messageViewModel.getSuperGroupInfo();
            boolean meIsAdministrator = messageViewModel.isGroupAdministrator(UserInfo.getUserInfo().id);
            if(meIsAdministrator){
                if(messageViewModel.isGroupAdministrator(userInfo.id)&&!messageViewModel.isGroupCreator(UserInfo.getUserInfo().id)){
                    sendmentionSpannable(userInfo);
                }else{
                    boolean heIsSilence = messageViewModel.isSilenceMember(userInfo.id);
                    new XPopup.Builder(getContext())
                            .hasShadowBg(false)
                            .atView(view).asAttachList(new String[]{getString(R.string.at_him_text), heIsSilence?getString(R.string.unmute_this_person):getString(R.string.mute_this_person), getString(R.string.delete_all_messages_from_this_person)}, new int[]{R.mipmap.group_handle_at,R.mipmap.group_handle_sil,R.mipmap.group_handle_delete}, new OnSelectListener() {
                                @Override
                                public void onSelect(int position, String text) {
                                    switch (position){
                                        case 0:
                                            sendmentionSpannable(userInfo);
                                            break;
                                        case 1:
                                            messageViewModel.banMemberFromSuperGroup(getContext(),conversation,userInfo,!heIsSilence);
                                            break;
                                        case 2:
                                            messageViewModel.delAllHisMessagesFromSuperGroup(getContext(),conversation,userInfo);
                                            break;
                                    }
                                }
                            }).show();
                }
            }else{
                sendmentionSpannable(userInfo);
            }
        }
    }

    public void sendReaction(UiMessage uiMessage,int reactionId){
        if(uiMessage==null||uiMessage.message == null||conversation==null){
            return;
        }
        MessageReaction reaction = uiMessage.haveReactionByCurrentUserId();
        TelegramManager.getTelegramManager().sendReaction(getContext(), conversation.id, conversation.isGroup() ? 2 : 1, uiMessage.message.id, reaction!=null&&reaction.reactionId==reactionId?0:reactionId, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {

            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    private void sendmentionSpannable(UserInfo userInfo){
        SpannableString spannableString = mentionSpannable(userInfo);
        int position = inputPanel.editText.getSelectionEnd();
        inputPanel.editText.getEditableText().append(" ");
        inputPanel.editText.getEditableText().replace(position, position + 1, spannableString);
    }

    private SpannableString mentionSpannable(UserInfo userInfo) {
        return mentionSpannable(userInfo,null);
    }

    private SpannableString mentionSpannable(UserInfo userInfo,String dmText) {
//        String nickName = conversation!=null&&conversation.isSuperGroup()?messageViewModel.getGroupNickNameByUserId(userInfo.id):userInfo.displayName();
        String nickName = conversation!=null&&conversation.isSuperGroup()?TelegramManager.getTelegramManager().getTgData().getUserRealyName(userInfo.id):userInfo.displayName();
        if(TextUtils.isEmpty(nickName)){
            nickName = userInfo.displayName();
        }
        String text = (!TextUtils.isEmpty(dmText)?String.format("%s@",dmText):"@") + nickName + " ";
        SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(new MentionSpan(String.valueOf(userInfo.id),!TextUtils.isEmpty(dmText)), 0, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    @Override
    public void onMessageReceiptCLick(MessageInfo message) {

    }
}
